package com.iraeta.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.common.*;
import com.iraeta.entity.main.User;
import com.iraeta.entity.main.vo.WeiXinOAuthLogin;
import com.iraeta.entity.main.vo.WeiXinUserInfo;
import com.iraeta.service.sys.UserService;
import com.iraeta.service.sys.impl.WeiXinService;
import com.iraeta.uitl.DesUtils;
import com.iraeta.uitl.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController(value = "UserController")
@RequestMapping("user")
public class UserController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;
    @Autowired
    WeiXinService weiXinService;

    @RequestMapping("wxlogin")
    @AuthAccess
    public String wxlogin(@RequestBody JSONObject paramJb){
        String wxcode = paramJb.getString("wxcode");
        if(wxcode == null){
            return JSONObject.toJSONString(Result.error("参数不正确"));
        }
        WeiXinOAuthLogin weiXinOAuthLogin = weiXinService.getUserIdByCode(wxcode);
        User user = userService.getUserByWxuid(weiXinOAuthLogin.getUserid());
        WeiXinUserInfo weiXinTickerUserInfo = null;
        if(user == null){
            weiXinTickerUserInfo = weiXinService.getWeiXinUserInfo(weiXinOAuthLogin.getUser_ticket());
            if(StrUtil.isEmpty(weiXinTickerUserInfo.getMobile())){
                return JSONObject.toJSONString(Result.error("企业微信" + weiXinOAuthLogin.getUserid() + "未绑定用户"));
            }
            user = userService.getUserByPhone(weiXinTickerUserInfo.getMobile());
            if(user == null){
                return JSONObject.toJSONString(Result.error("企业微信" + weiXinOAuthLogin.getUserid() + "未绑定用户"));
            }
        }
        if(StrUtil.isEmpty(user.getPhoto()) || !user.getPhoto().startsWith("https://wework.qpic.cn")){
            if(weiXinTickerUserInfo == null){
                weiXinTickerUserInfo = weiXinService.getWeiXinUserInfo(weiXinOAuthLogin.getUser_ticket());
            }
            //更新头像
            if(weiXinTickerUserInfo.getAvatar() !=null && !user.getPhoto().equals(weiXinTickerUserInfo.getAvatar())){
                user.setPhoto(weiXinTickerUserInfo.getAvatar());
                userService.updateUser(user);
            }
        }
        //生产token等数据
        Map<String,String> data = new HashMap<>();
        String token = JwtUtil.getToken(user.getId().toString());
        data.put("X-Token", token);
        data.put("userName", user.getName());
        return  JSONObject.toJSONString(Result.success(data));
    }

    @RequestMapping("login")
    @AuthAccess
    public String userLogin(@RequestBody JSONObject paramJb)throws Exception{
        String userName = paramJb.getString("username");
        String password_encrypt = paramJb.getString("password_encrypt");
        if(StrUtil.isEmpty(password_encrypt)){
            return JSONObject.toJSONString(Result.error("用户名密码不正确"));
        }
        String pwd = DesUtils.desDecript(password_encrypt);
        User user = userService.getUserByUserName(userName, pwd);
        if(user == null){
            return JSONObject.toJSONString(Result.error("用户名密码不正确"));
        }
        //生产token等数据
        Map<String,String> data = new HashMap<>();
        String token = JwtUtil.getToken(user.getId().toString());
        data.put("X-Token", token);
        return  JSONObject.toJSONString(Result.success(data));
    }

    @RequestMapping("info")
    public String userInfo(@RequestBody JSONObject paramJb){
        String token = paramJb.getString("X-Token");
        if(StrUtil.isEmpty(token)) {
            return JSONObject.toJSONString(Result.error("非法访问"));
        }
        int userId = this.getUserId();
        if(userId == 0){
            return JSONObject.toJSONString(Result.error("非法访问"));
        }
        Map<String,Object> data = new HashMap<>();
        data.put("name", this.getUserName());
        data.put("avatar", this.getUserAvatar());
        data.put("permissions", this.getPermissions());
        return JSONObject.toJSONString(Result.success(data));
    }

    @RequestMapping("logout")
    @AuthAccess
    public String userLogout(HttpServletRequest request){
        logger.info("logout");
        String token = request.getHeader("X-Token");
        MySessionManager.remove(token);
        return JSONObject.toJSONString(Result.success());
    }
}
